package com.yunyi.user.service.impl;

import cn.binarywang.wx.miniapp.api.WxMaService;
import com.google.common.base.Joiner;
import com.google.common.collect.Maps;
import com.yunyi.model.mappers.media.FileMediaMapper;
import com.yunyi.model.media.FileMedia;
import com.yunyi.user.constant.Constant;
import com.yunyi.user.service.FileSystemService;
import me.chanjar.weixin.common.bean.ocr.WxOcrBankCardResult;
import me.chanjar.weixin.common.bean.ocr.WxOcrIdCardResult;
import me.chanjar.weixin.common.service.WxOcrService;
import org.apache.commons.io.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Date;
import java.util.Map;

/**
 * @ClassName FileSystemServiceImpl
 * @Description 文件管理
 * @Author leizhang
 * Date 2021/8/18 11:27 上午
 * @Version 1.0
 **/
@Service
public class FileSystemServiceImpl implements FileSystemService {
    private static Logger LOGGER = LoggerFactory.getLogger(FileSystemServiceImpl.class);
    @Autowired
    private FileMediaMapper fileMediaMapper;
    //字符串连接器
    private final Joiner joiner = Joiner.on("/").skipNulls();
    @Value("${pic.url}")
    private String url;
    @Value("${pic.uploadLocation}")
    private String upload_location;
    @Value("${ocr.flag}")
    private boolean ocr;
    @Autowired
    private WxMaService wxMaService;


    //得到文件的路径
    private String getFilePath(String fileMd5, int imgType, String fileExt) {
        return upload_location + joiner.join(new String[]{fileMd5.substring(1, 4)}).concat("/") + fileMd5.concat("-").concat(imgType + "") + "." + fileExt;
    }

    private String getFilePathNoExt(String fileMd5, int imgType) {
        return upload_location + fileMd5.substring(1, 4).concat("/");
    }

    private String getFileUrlPath(String fileMd5, int imgType, String fileExt) {
        return fileMd5.substring(1, 4).concat("/") + fileMd5.concat("-").concat(imgType + "") + "." + fileExt;
    }

    /**
     * @param fileMedia
     * @return void
     * @Description : 文件管理系统
     * @Author : leizhang
     * @Date 11:28 上午 2021/8/18
     **/
    @Override
    public void saveFileSystem(FileMedia fileMedia) {
        fileMediaMapper.saveFileMedia(fileMedia);
    }

    /**
     * @param imgType
     * @param file
     * @param openid
     * @param mimeType
     * @return int
     * @Description : 系统图片上传
     * @Author : leizhang
     * @Date 1:50 下午 2021/8/18
     **/
    @Override
    public Map<String,Object> uploadFile(int imgType, MultipartFile file, String openid, String mimeType) throws Exception {
        Map<String,Object> resultResult = Maps.newHashMap();

        //获取文件的原始名称  截取到 扩展名 文件原始名称
        String fileOrgName = file.getOriginalFilename();
        //文件扩展名称
        String ext = fileOrgName.substring(fileOrgName.lastIndexOf(".") + 1);
        //文件原始名称
        String fileName = fileOrgName.substring(0, fileOrgName.indexOf("."));
        //以为用户的openid 拼接的新名称
        String newFileName = Joiner.on(".").join(openid.concat("-".concat(imgType + "")), ext);
        String filePath = getFilePath(openid, imgType, ext);
        //判断文件是否存在
        File uploadFIle = new File(getFilePathNoExt(openid, imgType));
        if (!uploadFIle.exists()) {
            //不存在就创建
            uploadFIle.mkdir();
        }
        try (InputStream inputStream = file.getInputStream();
             FileOutputStream outputStream = new FileOutputStream(new File(filePath))) {
            IOUtils.copy(inputStream, outputStream);
        } catch (IOException ioException) {
            //流自动关闭
            LOGGER.error("图片上传失败:[{}]", ioException.getMessage(), ioException);
            throw new Exception(ioException.getMessage());
        }
        //3.保存文件
        FileMedia mediaFile = new FileMedia();
        mediaFile.setFileOriginalName(fileOrgName);
        mediaFile.setFileName(newFileName);
        //文件路径保存相对路径
        String filePath1 = openid.substring(1, 4).concat("/") + newFileName;
        mediaFile.setFilePath(filePath1);
        mediaFile.setFileSize(file.getSize());
        mediaFile.setUploadTime(new Date());
        mediaFile.setMimeType(mimeType);
        mediaFile.setFileType(ext);
        //状态为上传成功 上传状态 1 表示上传成功 0 表示文件上传失败
        mediaFile.setFileStatus(1);
        //图片的访问路劲
        mediaFile.setFileUrl(url.concat(filePath1));
        mediaFile.setProcessStatus(1);
        mediaFile.setTag(imgType);
        this.saveFileSystem(mediaFile);
        //结果值封装
        resultResult.put(Constant.ID,mediaFile.getId());
        //开启ocr识别 WxOcrService
        if (ocr) {
            try {
                WxOcrService ocrService = wxMaService.getOcrService();
                File imgFile = new File(filePath);
                switch (imgType){
                    case 1 :
                        WxOcrIdCardResult wxOcrIdCardResult = ocrService.idCard(imgFile);
                        resultResult.put(Constant.ID_CARD_IMG_INFO,wxOcrIdCardResult);
                        break;
                    case 2:
//                        WxOcrBankCardResult wxOcrBankCardResult = ocrService.bankCard(imgFile);
//                        resultResult.put(Constant.BANK_IMG_INFO,wxOcrBankCardResult);
                        WxOcrIdCardResult wxOcrBankCardResult = ocrService.idCard(imgFile);
                        resultResult.put(Constant.BANK_IMG_INFO,wxOcrBankCardResult);
                        break;
                }
            }catch (Exception e){
                LOGGER.error("ocr图像识别错误信息:[{}]",e.getMessage(),e);
            }
        }
        return resultResult;
    }
}
